package com.factory.iamp.service.impl;

import com.factory.iamp.dao.LineMapper;
import com.factory.iamp.pojo.*;
import com.factory.iamp.service.LineService;
import com.factory.iamp.utils.exception.APIException;
import com.factory.iamp.utils.helper.ResponseCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Throwable.class)
public class LineServiceImpl implements LineService {
    @Resource
    private LineMapper lineMapper;

    @Override
    public List<LineWithInfo> getAllLine(String uid) {
        return lineMapper.getAllLine(uid);
    }

    @Override
    public int getMemberCountInLine(int lid) {
        return lineMapper.getMemberCountInLine(lid);
    }

    @Override
    public List<LineUserList> getMemberInLine(int lid, int offset, int limit) {
        return lineMapper.getMemberInLine(lid, offset, limit);
    }

    @Override
    public LinePermission getLinePermission(String uid, int lid) {
        return lineMapper.getPermission(lid, uid);
    }

    @Override
    public void addMember(int lid, String uid, String r, String w, String a) {
        LinePermission res = lineMapper.getPermission(lid, uid);
        if(res != null) {
            lineMapper.renewPermission(lid, uid, r, w, a);
        } else lineMapper.addMember(lid, uid, r, w, a);
        if(r.equals("0") && w.equals("0") && a.equals("0")) lineMapper.deleteMember(lid, uid);
    }

    @Override
    public void changeLine(int lid, User user) {
        LinePermission linePermission = lineMapper.getPermission(lid, user.getUid());
        if(linePermission == null) {
            if(user.isAdmin()) {
                addMember(lid, user.getUid(), "1", "1", "0");
                linePermission = new LinePermission(lid, user.getUid(), 1, 1, 0);
            }
            else throw new APIException(ResponseCode.LINE_PERMISSION_DENIED, "没有产线权限信息");
        }
        if(!linePermission.checkPermission("r"))
            throw new APIException(ResponseCode.LINE_PERMISSION_DENIED, "没有产线读取权限");
        lineMapper.changeLine(lid, user.getUid());
    }

    @Override
    public void addLine(String name, String uid) {
        lineMapper.addLine(name);
        addMember(lineMapper.getLidByName(name), uid, "1", "1", "1");
    }

    @Override
    public void setLine(int lid, Map<String, String> data) {
        lineMapper.setLine(lid, data.get("name"));
    }

    @Override
    public void setLinePermission(int lid, Map<String, String> data) {
        addMember(lid, data.get("uid"), data.get("r"), data.get("w"), data.get("a"));
    }

    @Override
    public void deleteLine(int lid) {
        lineMapper.deleteLine(lid);
    }
}
